<template>
  <div class='piaomake'>
    <!-- <a class="goTop" href="#">返回顶部</a> -->
    <div style="position: relative;">
      <div class="clearfix" style="margin-bottom: 6px;">

        <div style="float: right;">
          <el-button
            type="success"
            size="mini"
            @click="goBack"
          >返回
          </el-button>
    
          <el-button
            type="primary"
            size="mini"
            @click="handleApprove(1)"
            v-if="type=='3'"

          >审批通过
          </el-button>

          <el-button
            type="danger"
            size="mini"
            @click="handleApprove(2)"

            v-if="type=='3'"
          >审批拒绝
          </el-button>
        </div>
      </div>
    </div>
    <template>
      <!---->
        <el-form ref="form" :model="form" label-width="99px"  >
            
           <h2>基本信息</h2>
            <el-row>
              <el-col :span="6" >
                <el-form-item label="开票申请人" prop="createName">
                  <el-input v-model="form.createName" :disabled="true">
                  </el-input>
                </el-form-item>
              </el-col>
              

              <el-col :span="12" >
                <el-form-item label="申请部门" prop="deptId">
                  <tree-select v-if="type == 1" :disabled="true" v-model="form.deptId" :options="departmentAllListData" :normalizer="treeSelectProps"
                     placeholder="选择部门" style="height:22px;line-height:22px;"
                     />

                     <el-input v-else v-model="form.applyDeptName" :disabled="true">
                    </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6" >
                <el-form-item label="费用所属月" prop="expenseMonth">
                    <el-date-picker clearable size="small" style="width: 200px"
                      v-model="form.expenseMonth"
                      :disabled="type == 3 "
                      type="month"
                      value-format="yyyy-MM"
                      placeholder="请选择费用所属月">
                    </el-date-picker>
                  </el-form-item>
              </el-col>

               </el-row>
            <el-row>

          
            <el-col :span="6" >
                <el-form-item label="项目名称" prop="projectName">
                  <el-input :disabled="true" v-model="form.projectName">
                  </el-input>
                </el-form-item>
              </el-col>
   
            
              <el-col :span="6" >
                <el-form-item label="项目编号" prop="projectNo">
                  <el-input :disabled="true" v-model="form.projectNo">
                  </el-input>
                </el-form-item>
              </el-col>

             
              <el-col :span="6" >
                <el-form-item label="合同编号" prop="contractNo">
                  <el-input :disabled="true" v-model="form.contractNo">
                  </el-input>
                </el-form-item>
              </el-col>

            </el-row>

            <h2 style="margin-top:0px;">开票信息</h2>
            <el-row>
               <el-col :span="12" >
                <el-form-item label="我方开票公司" prop="ourInvoiceCompany" label-width="120px">
                  <el-select
                    v-model="form.ourInvoiceCompany"
                    placeholder="开票类型"
                    clearable
                    :disabled="true"
                    size="small"
                    style="width:100%"
                  >
                    <el-option label="请选择我方开票公司" value=""></el-option>
                      <el-option v-for="(item, index) in invoiceCompanyAllListData"
                                :key="`invoiceCompany${index}`"
                                :label="item.dictLabel"
                                :value="item.dictValue">
                      </el-option>
                    
                  </el-select>
                </el-form-item>
              </el-col>
            
            

              <el-col :span="12" >
                <el-form-item label="收票联系人" prop="invoiceReceiverName" label-width="120px">
                  <el-input :disabled="true" v-model="form.invoiceReceiverName" >
                  </el-input>
                </el-form-item>
              </el-col>

                </el-row>
            <el-row>
            
              <el-col :span="12" >
                <el-form-item label="联系地址" prop="invoiceReceiverAddress" label-width="120px">
                  <el-input :disabled="true" v-model="form.invoiceReceiverAddress">
                  </el-input>
                </el-form-item>
              </el-col>
            

              <el-col :span="12" >
                <el-form-item label="联系人电话" prop="invoiceReceiverPhone" label-width="120px" >
                  <el-input :disabled="true" v-model="form.invoiceReceiverPhone">
                  </el-input>
                </el-form-item>
              </el-col>


            </el-row>

            <h2 style="margin-top:0px;color:#929191;">费用说明</h2>
            <el-row>
                <el-col :span="5" >
                  <el-form-item label="工资费用" prop="salaryExpense">
                    <el-input :disabled="true" v-model="form.salaryExpense">
                    </el-input>
                  </el-form-item>
                </el-col>
              <el-col :span="5" >
                  <el-form-item label="社保费用" prop="socialSecurityExpense">
                    <el-input :disabled="true" v-model="form.socialSecurityExpense">
                    </el-input>
                  </el-form-item>
                </el-col>

             
                <el-col :span="5" >
                  <el-form-item label="管理费用" prop="managementExpense">
                    <el-input :disabled="true" v-model="form.managementExpense">
                    </el-input>
                  </el-form-item>
                </el-col>
           
              <el-col :span="5" >
                 <el-form-item label="其他费用" prop="otherExpense">
                    <el-input :disabled="true" v-model="form.otherExpense">
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="4" >
                 <el-form-item label="合计" prop="totalExpense" label-width="50px">
                    <el-input v-model.trim="totalExpense" :disabled="true">
                    </el-input>
                  </el-form-item>
                </el-col>
            
            </el-row>
            <h2 style="margin-top:0px;color:#929191;">其他</h2>
            <el-row>
                <el-col :span="8" >
                  <el-form-item label="开票备注" prop="remark">
                    <el-input :disabled="true" type='textarea' v-model.trim="form.remark" class="edit-input" 
                          style="width: 480px"/>
                  </el-form-item>
                  
                </el-col>

            </el-row>

            <!-- <h2 style="margin-top:0px;color:#929191;">其他</h2>
            <el-row>
                <el-col :span="15" >
                  <el-form-item label="开票备注" prop="remark">
                    <el-input :disabled="true" type='textarea' v-model.trim="form.remark" class="edit-input" 
                          style="width: 100%"/>
                  </el-form-item>
                  
                </el-col>

            </el-row> -->

            <!-- <el-row>
            <el-col :span="24" style="margin-bottom:100px;">
              <el-form-item label="" prop="applyFiles">
              <div style="display: inline-block;float:left;">
                <ul class="el-upload-list el-upload-list--picture-card" style="float: left; height: 25px;margin-top:-80px;">
                  <li tabindex="0" class="el-upload-list__item"
                      v-for="(item,index) in form.applyFilesListData"
                      :key="`applyFiles${index}`">
                    <p>{{item.fileName}}</p>
                    <div class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="handleExportApplyFiles(item.id)"><i
                            class="el-icon-download"></i></span>
                      <span class="el-upload-list__item-delete" @click="handleRemoveApplyFiles(index)"><i
                        class="el-icon-delete"></i></span>
                    </div>
                  </li>
                </ul>
              </div>
               </el-form-item>
              
              <div id="laborContract-box"
                   style="position: relative; display: inline-block; width: 70px; height: 70px;">
                <div id="upload-laborContract" class="el-upload el-upload--picture-card"
                     style="display: inline-block;">
                  <i class="el-icon-plus"></i>
                </div>
              </div>
            </el-col>
            <el-col :span="24" style="margin-bottom:20px;">
              <div style="color: #999;">提示：请上传PDF文档！</div>
            </el-col>
          </el-row> -->
            <span v-if="type == 3" style="position:relative;top:16px;float:left;" >附件列表:</span>
            <el-row style="margin-bottom:40px;margin-top:40px;">
                <el-col :span="24">
                    <el-upload
                       v-loading="uploadLoading"
                       element-loading-text="正在下载,请稍后..."
                      style="left"
                      class="upload-demo"
                      :action="uploadUrl"
                      :headers="headers"
                      :data="{modelName :'开票申请',employeePhone:'123'}"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      multiple
                      
                      :file-list="fileList">
                      <el-button v-if="type != 3" size="small" type="warning">附件上传</el-button>
                      
                      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                    </el-upload>
                </el-col>

            </el-row>

            <el-row>
              <el-col :span="24" >

                 <el-button  v-if="type != '3'" size="small" type="primary" icon="el-icon-add" @click="handleAdd">新增</el-button>

                  <el-table
                    class="list-table"
                    ref="table"
                    :key="tableKey"
                    v-loading="listLoading"
                    :data="listData"
                    stripe
                    size="small"
                    fit
                    show-summary
                    :summary-method="handlePiaoSummaries"
                    highlight-current-row 
                    >

                    <el-table-column :show-overflow-tooltip="false" prop="receiveCompanyName"
                                    label="" width="250">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">收票单位全称</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="true" v-model="scope.row.receiveCompanyName" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'receiveCompanyName')"
                                    style="width: 230px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="taxpayerIdentificationNumber"
                                    label="" width="200">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">纳税人识别号</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input  type="textarea"  :disabled="true" maxlength='18' v-model="scope.row.taxpayerIdentificationNumber" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'taxpayerIdentificationNumber')"
                                    style="width: 190px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="addressAndPhone"
                                    label="" width="250">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">地址与电话</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="true" v-model="scope.row.addressAndPhone" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'addressAndPhone')"
                                    style="width: 230px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="openingBankAndNo"
                                    label="" width="250">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开户行及账号</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="true" v-model="scope.row.openingBankAndNo" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'openingBankAndNo')"
                                    style="width: 230px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>


                    <el-table-column :show-overflow-tooltip="false" prop="invoicetype"
                                    label="" width="450">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开票类型</p>
                      </template>
                      <template slot-scope="scope">
                        <template>

                         <el-cascader 
                              v-model="scope.row.invoiceType" 
                              :options="invoiceTypeOptions" 
                              @change="invoiceTypeSelect"
                              :disabled="true"
                              style="width:100%"
                              :show-all-levels="true">
                          </el-cascader> 

                          <!-- <el-input v-model="scope.row.invoiceContent" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'invoiceContent')"
                                    style="width: 130px;"/> -->
                           <!-- <el-select v-model="scope.row.invoiceType" placeholder="选择开票类型" style="width:160px">
                            <el-option label="选择开票类型" value=""></el-option>
                            <el-option label="代收代付" value="0" />
                           <el-option label="代发工资" value="1" />
                           
                          </el-select> -->

                        </template>
                        
                      </template>
                    </el-table-column>

                    <!-- <el-table-column :show-overflow-tooltip="false" prop="amount"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">数量</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input v-model.number="scope.row.amount" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'amount')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column> -->

                    <el-table-column :show-overflow-tooltip="false" prop="includeTaxMoney"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开票金额（含税）</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input :disabled="true" v-model="scope.row.includeTaxMoney" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'includeTaxMoney')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="otherMoney"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">其中其他金额</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input :disabled="true" v-model="scope.row.otherMoney" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'otherMoney')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="taxMoney"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">税额</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input :disabled="true" v-model="scope.row.taxMoney" class="edit-input" size="small" 
                                    @blur="handleChangeInputValue(scope, ' taxMoney')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="remark"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">备注说明</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="true" v-model="scope.row.remark" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'remark')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column ref="actionColumn" fixed="right" align="left" label="" 
                        width="1"
                         class-name="small-padding fixed-width">
                      <template slot-scope="scope">
                        <el-button ref="actionDelete"
                                  type="danger"
                                  size="mini"
                                  icon="el-icon-remove"
                                  :disabled="true"
                                  @click="handleDelete(scope.row,scope.$index)"
                                  v-hasPermi="['hr:employee:remove']"></el-button>
                        <slot name="rights" :row-data="scope.row"></slot>
                      </template>
                    </el-table-column>


                  </el-table>
              </el-col>
            </el-row>

            <!-- <el-row style="margin-top:20px;">
              <el-col :span="8" >
                <el-form-item label="开票时间" prop="pid">
                  <el-input v-model="form.xxx">
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="8" >
                <el-form-item label="邮寄日期" prop="pid">
                  <el-input v-model="form.xxx">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" >
                <el-form-item label="合计开票金额" prop="pid">
                    <el-input v-model="form.xxx">
                    </el-input>
                  </el-form-item>
              </el-col>
            </el-row> -->
            
            
       


        </el-form>

        <el-dialog title="请输入拒绝原因" :visible.sync="openReasonInput" width="650px">

          <el-row :gutter="20">

            <el-col :span="16" :offset="2">

              <el-input
                type="textarea"
                v-model="remark"
                :rows="7"
                placeholder="请输入审核意见"
                clearable
                size="small"
                style="margin-bottom: 20px;"
              />

            </el-col>
          </el-row>

          <div slot="footer" class="dialog-footer">
            <el-button type="danger" @click="handleEditRejectSubmit2">确认审批拒绝</el-button>
            <el-button @click="openReasonInput = false">取消</el-button>
          </div>

        </el-dialog>

    </template>

    </div>
  </div>
  
</template>

<script>
  import { debounce } from 'lodash'
  import { create, all } from 'mathjs'
  import numeral from 'numeral'
  import commonMixins from '@/mixins/common'
  import salaryMixins from '@/mixins/salary'
  import filters from '@/filters/filters'
  import tagFilter from '@/filters/tagFilter'
  import salaryImportExcel from '@/mixins/salaryImportExcel'

  import { getUserProfile } from "@/api/system/user";
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import upload from '@/mixins/upload'
  import request from '@/utils/request'
  import { formatMoney } from '@/utils/utils'
  import { getToken } from '@/utils/auth'
  import {fileDownloadAPI} from '@/api/common.js'

  let baseUrl = process.env.NODE_ENV === 'development' ? `${process.env.VUE_APP_BASE_API}` : `${process.env.VUE_APP_API_PATH}${process.env.VUE_APP_BASE_API}`

  let math = create(all, {
    number: 'BigNumber',
    precision: 64
  })

 let isCurrency = /^(([1-9]\d*)|0)(\.\d{1,2})?$/

  export default {
    name: '',
    mixins: [commonMixins, salaryMixins, filters, tagFilter, salaryImportExcel,upload],
    components: {TreeSelect},
    data() {
      return {
        uploadLoading:false,
        form:{},
        remark:'',
         openReasonInput: false,


        leafNodes:[],
        fileList: [] ,
        
        uploadUrl: `${baseUrl}tool/file/uploadFile`,
        headers: {
          Authorization: 'Bearer ' + getToken()
        },

        invoiceTypeOptions:[],

        rules : {

          projectNo: [
              { required: true, message: '请输入项目编号', trigger: 'blur' }
            ],

          contractNo: [
              { required: true, message: '请输入合同编号', trigger: 'blur' }
            ],

          projectName: [
              { required: true, message: '请输入项目名称', trigger: 'blur' }
            ],

          deptId: [
              { required: true, message: '请输入申请部门', trigger: 'blur' }
            ],

            ourInvoiceCompany: [
              { required: true, message: '请输入我方开票公司', trigger: 'blur' }
            ],

            invoiceType: [
              { required: true, message: '请输入发票类型', trigger: 'blur' }
            ],

            invoiceReceiverName: [
              { required: true, message: '请输入收票人姓名', trigger: 'blur' }
            ],

            invoiceReceiverAddress: [
              { required: true, message: '请输入收票人地址', trigger: 'blur' }
            ],

            invoiceReceiverPhone: [
              { required: true, message: '请输入收票人电话', trigger: 'blur' }
            ],

          salaryExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入工资费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],

            socialSecurityExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入社保费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],

            managementExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入管理费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],

             otherExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入其他费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],


        },
        user:{}, //当前登录人
        form:{
          applyFilesListData:[],
        },
        title: this.paramsData.title,
        searchKey: {},
        isExpand: true,
         treeSelectProps(node) {
          return {
            id: node.id,
            label: node.label,
            children: node.children,
            isDefaultExpanded: true
          }
        },
        tableSelectedData: [], // 选中的表数据
        listData: [] // 列表数据
      }
    },
    props: {

      invoiceTypeOptions:{
          type: Array,
          required: true,
          default() {
            return []
          } 
      },
      
      invoiceCompanyAllListData:{
         type: Array,
          required: true,
          default() {
            return []
          } 
      },
      data: { // 列表数据
        type: Array,
        required: true,
        default() {
          return []
        }
      },
      formData:{ 
        type: Object,
        required: true,
        default() {
          return {}
        }
      },
      searchParams: { // 搜索参数
        type: Object,
        required: true,
        default() {
          return {}
        }
      },
      totalCount: {
        type: [String, Number],
        required: true,
        default: 0
      },
      listLoading: {
        type: [Boolean],
        required: true,
        default: false
      },
      type: {
        type: [String],
        required: true,
        default: '1'
      },
      deptName: {
        type: [String],
        default: '-'
      },
      salaryDate: {
        type: [String],
        default: '-'
      },

      paramsData: {
        type: Object,
        required: true,
        default() {
          return {}
        }
      },

      departmentAllListData: {// 搜索参数
        type: Array,
        required: true,
        default() {
          return []
        }
      }
    },
    computed: {
      totalExpense() {
        let salaryExpense = this.form.salaryExpense || 0
        let socialSecurityExpense = this.form.socialSecurityExpense || 0
        let managementExpense = this.form.managementExpense || 0
        let otherExpense = this.form.otherExpense || 0
        let result = parseFloat(this.formatNumberTiny({
                formula: `${salaryExpense} + ${socialSecurityExpense} + ${managementExpense} + ${otherExpense}`, format: '0.00'
              }))
        return result
      },
      currentListData() { // 当前的数据列表
        let { listData, totalCount } = this
        let { pageNum, pageSize } = this.searchKey
        let totalPage = 0 //总页数
        if ((totalCount / pageSize) > parseInt(totalCount / pageSize)) {
          totalPage = parseInt(totalCount / pageSize) + 1
        } else {
          totalPage = parseInt(totalCount / pageSize)
        }
        //对数据进行分页
        let startRow = (pageNum - 1) * pageSize
        let endRow = (pageNum * pageSize > totalCount ? totalCount : pageNum * pageSize) - 1
        return listData.filter((item, index) => {
          return startRow <= index && index <= endRow
        })
      }
    },
    methods: {

      handlePiaoSummaries(param){
            let { listData } = this
            let { columns } = param
            let sums = []
            let keys = ['includeTaxMoney','otherMoney','taxMoney']
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '合计'
                return
              }
              const values = listData.map(item => item[column.property] || 0)
              if (keys.indexOf(column.property) !== -1 && !values.every(value => isNaN(value))) {
                
                sums[index] = values.reduce((prev, curr) => {
                  let value = Number(curr)
                  if (!isNaN(value)) {
                    let result = math.format(math.evaluate(`${prev} + ${curr}`))
                    return result
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] = formatMoney(sums[index], 2, '') + ' 元'

                // if(column.property == 'includeTaxMoney'){
                //    window.includeTaxMoneyAll = formatMoney(sums[index], 2, '¥').replace('¥','')
                // }

              } else {
                sums[index] = ''
              }
            })
            return sums
        },

        handleChange(file, fileList){
          this.fileList = fileList
        },

        handleRemove(file, fileList) {
          console.log(file, fileList);
          this.fileList = fileList
        },
        async handlePreview(file) {
          console.log(file);
          this.uploadLoading = true;
          try {
            let response = await fileDownloadAPI({
              fileName: file.response.data.id
            })
            this.downloadFile(response)
          } catch (error) {
            this.$notify.error({
              title: '错误',
              message: error.message || '导出失败!'
            })
          } finally{
            this.uploadLoading = false;
          }
        
        },
        handleExceed(files, fileList) {
          //this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
          this.fileList = fileList
        },
        beforeRemove(file, fileList) {
          if(this.type == 3) return false;
          return this.$confirm(`确定移除 ${ file.name }？`);
        },

      handleExportApplyFiles(data) { // 导出附件
        this.$emit('on-export', {
          name: this.applyFilesName,
          fileName: data
        })
      },

       handleRemoveApplyFiles(index) { // 删除
        this.form.applyFilesInstance.splice(index, 1)
        this.form.applyFilesListData.splice(index, 1)
      },

      /**
       * 开票明细删除
       */
      handleDelete(data = {},index) {
         this.listData.splice(index,1)
      },

      getUser() {
        getUserProfile().then(response => {
          this.user = response.data;
          //console.log(this.user);
        });
      },

      goBack() {
        this.$store.dispatch("tagsView/delView", this.$route);
        history.back()
      },

      beforeSaveFlag(){
          let submitData = {}

        //开票明细数据处理
        let listData = this.listData || []
        let fields = ['addressAndPhone','invoiceType','includeTaxMoney','openingBankAndNo','otherMoney','receiveCompanyName','remark','taxpayerIdentificationNumber','taxMoney'];
        let flag = true;
        let errMsg = '';
        for(let i=0;i<listData.length;i++){
            let row = listData[i];
            fields.map((v,k) => { 
                let value = row[v];
                if(!value){
                  flag = false;
                  errMsg = '发票明细数据填写不完整，请核对！'
                }

                if('otherMoney' == v || 'includeTaxMoney' == v || 'taxMoney' == v) {
                  if( !isNumber(row[v])){
                    //console.log(row[v] + '不是数字');
                    flag = false;
                    errMsg = '开票明细中金额填写不正确(最多两位小数)，请核对！'
                  }
                 
                 if((''+row[v]).split('.')[1] && (''+row[v]).split('.')[1].length > 2){
                   flag = false;
                  errMsg = '开票明细填写不正确(最多两位小数)，请核对！问题数据：' + row[v]
                 }
                  
                }

                if('invoiceType' == v ) {
                   if(row[v][2]) row[v] = row[v][2]
                }

              
            });
            
        }

        if(!flag){
            this.$notify.error({
                    title: '错误',
                    message: errMsg
                  });
            return false;
        }

        

        return true;
      },

      handleSave: debounce(function() { // 保存，防抖


        if(!this.beforeSaveFlag()) return;
        
        //console.log('开票明细',this.listData);   
        
        //开票信息表单校验
        this.$refs['form'].validate(valid => {
            let submitData = this.form;
              submitData.hrInvoiceDetails = this.listData;

             this.$emit('on-save',submitData)
        });

      }, 300),
      // handleApprove() { // 是否审批

      //   if(!this.beforeSaveFlag()) return;
      //   //console.log('开票明细',this.listData);   
        
      //   //开票信息表单校验
      //   this.$refs['form'].validate(valid => {
      //       let submitData = this.form;
      //         submitData.hrInvoiceDetails = this.listData;
      //        this.$emit('on-approve',submitData)
      //   });


        
      // },


    handleApprove(option) { // 审批
        let query = this.$route.query
        let taskId = query.taskId
        let msg = option == 1 ? ' <b><font color=green>通过</font></b> ' : ' <b><font color=red>拒绝</font></b> '

        this.$confirm('审批操作不可撤销,请认真审核,您确定要' + msg + '吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          /*let params = this.formatParams()
          this.submitApproveData(params)*/

          if (option == 1) {
            //审批通过就直接提交

            let auditOpinion = prompt('请输入审批意见！');

            request({
              url: '/hr/invoice/apply/audit',
              method: 'post',
              data: {
                taskId: taskId,
                auditOpinion: auditOpinion || '同意',
                auditResult: 1
              }
            }).then(response => {
              if (response.code != '200') {
                this.msgError('审批失败，原因是' + response.data.msg)
                return
              }

              if (response.data.receiveDeptName) {
                this.msgSuccess(response.data.msg + '，下一步办理人【' + response.data.receiveDeptName + '】【' + response.data.receiverName + '】')
              } else {
                this.msgSuccess(response.data.msg)
              }
              //this.msgSuccess(response.data.msg+'，下一步办理人【'+response.data.receiveDeptName+'】【'+response.data.receiverName+'】');
              let that = this
              setTimeout(() => {
                that.goBack()
              }, 2000)

            })

          } else {
            //审批拒绝需要填写拒绝原因
            this.openReasonInput = true
          }

        })
      },


      handleEditRejectSubmit2() {
        if (!this.remark) {
          this.msgError('请填写拒绝原因！')
          return
        }

        let query = this.$route.query
        let taskId = query.taskId

        request({
          url: '/hr/invoice/apply/audit',
          method: 'post',
          data: {
            taskId: taskId,
            auditOpinion: this.remark,
            auditResult: 0
          }
        }).then(response => {
          if (response.code != '200') {
            this.msgError('审批失败，原因是' + response.data.msg)
            return
          }

          if (response.data.receiveDeptName) {
            this.msgSuccess(response.data.msg + '，下一步办理人【' + response.data.receiveDeptName + '】【' + response.data.receiverName + '】')
          } else {
            this.msgSuccess(response.data.msg)
          }

          let that = this
          setTimeout(() => {
            that.goBack()
          }, 2000)

        })

      },


      handleExport: debounce(function() { // 导出，防抖
        this.$emit('on-export')
      }, 300),

      handleImport() { // 导入
        
        this.$emit('on-import')
      },

      handleAdd(){
        if(!this.listData) this.listData = []
        this.listData.push({});
      },


      handleChangeInputValue(data, key) {

        let isCurrency = /^(([1-9]\d*)|0)(\.\d{1,2})?$/
        let { pageNum, pageSize } = this.searchKey
        let { row } = data
        let listDataIndex = (pageNum - 1) * pageSize + data.$index
        
        this.$set(this.listData[listDataIndex], key, row[key])
        
      },
      changeTitle(e) {
        this.$forceUpdate() //我也不明白为什么，就是无法输入，只能这样了
      }
    },
    watch: {
      data: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.listData)) {
            this.listData = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      },
      formData: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.form)) {
            //console.log(newVal)
            this.form = JSON.parse(JSON.stringify(newVal))
            this.listData = this.form.hrInvoiceDetails

            this.fileList = JSON.parse(this.form.applyFiles)

            //回显开票类型
            for(let i=0;i<this.listData.length;i++){
                let row = this.listData[i];
                row.invoiceType = row.invoiceTypePids.split(',');
            }
            
          }
        },
        deep: true,
        immediate: true
      },

      searchParams: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
            this.searchKey = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      },

      paramsData: {

        handler: function(newVal, oldVal) {

          if (JSON.stringify(newVal) !== JSON.stringify(this.paramsData)) {
            this.paramsData = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
          // 附件初始化
          this.initPlupload({
            container: 'laborContract-box',
            selectFiles: 'upload-laborContract',
            // mimeTypes: [
            //   { title: 'files', extensions: 'pdf' }
            // ],
            //employee: this.formValue
          }).then((instance) => {
            this.form.applyFilesInstance = instance
            this.form.applyFilesInstance.init()
            this.form.applyFilesInstance.bind('handleBeforeUpload', (up) => {
              up.disableBrowse(true)
            })
            this.form.applyFilesInstance.bind('handleUploadProgress', (up, filePercent) => {
              //this.form.laborContractPercent = filePercent
            })
            this.form.applyFilesInstance.bind('handleFileUploaded', (up, fileInfo) => {
              // up.splice(0, 1)
              this.form.applyFilesListData.push(fileInfo)
            })
            this.form.applyFilesInstance.bind('handleInitPercent', (up) => {
             // this.editInfo.data.laborContractPercent = 0
              //this.form.laborContractUpload = false
              up.disableBrowse(false)
            })
          }).catch((error) => {
            this.$notify.error({
              title: '错误',
              message: error.message
            })
          })

    },
    mounted() {
      this.getTableColumns()
      this.getUser()
    }
  }


  function isNumber(val){

          var regPos = /^\d+(\.\d+)?$/; //非负浮点数
          var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
          if(regPos.test(val) || regNeg.test(val)){
              return true;
          }else{
              return false;
          }

      }
</script>

<style lang="scss" >
  .list-table {
    .el-button--mini {
      padding: 7px 15px;
      width: 45px;
      color: #fff;
    }

    & /deep/ .el-table__header-wrapper {
      th {
        background-color: #fff;
      }
    }
  }

   .piaomake {

  h2 {
    font-size: 18px;
    font-weight: 500;
    border-bottom: 1px solid #eaeaea;
    padding-bottom: 4px;
    margin-top:0px;color:#929191;
  }

   .el-popover {
    max-height: 400px;
    overflow-x: auto;
    overflow-y: scroll;
  }

  .goTop {
    display: inline-block;
    padding: 14px 2px;
    background: #eaeaea;
    border: 1px solid #ccc;
    position: fixed;
    right: 2px;
    bottom: 280px;
    z-index: 8;
    cursor: pointer;
  }

  .el-form-item__label {
      font-size: 13px;
  }

  .el-input--medium .el-input__inner {
    height: 30px;
    line-height: 30px;
}

.el-upload-list {
    margin: 0;
    padding: 0;
    list-style: none;
    float: left;
}

.el-upload-list__item {
  width: auto;
  margin-right: 20px;
  padding: 2px 6px;
  border: 1px solid #ccc;
  display: inline-block;
}

.el-upload-list__item-name {
  display: inline;
}

.el-upload {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: none;
    float: left;
    margin-right: 10px;
    margin-top: 10px;
    margin-left: 20px;
    
}



.el-input.is-disabled .el-input__inner {
    background-color: #F5F7FA;
    border-color: #dfe4ed;
    color: #000001 !important;
   

}

.el-textarea__inner {
    background-color: #FFF;
    border-color: #dfe4ed;
    color: #000001 !important;
    

}

.el-input.is-disabled .el-input__inner {
    background-color: #F5F7FA;
    border-color: #dfe4ed;
    color: #000;

}

.el-table .fixed-width .el-button--mini {
    color: #fff;
    padding: 6px 16px;
    width: inherit;
}

}

</style>



